//初始化我的最近会话表格
function initGetRecentContactListTable(data) {
    $('#get_recent_contact_list_table').bootstrapTable({
        method: 'get',
        cache: false,
        height: 500,
        striped: true,
        pagination: true,
        pageSize: pageSize,
        pageNumber: 1,
        pageList: [10, 20, 50, 100],
        search: true,
        showColumns: true,
        clickToSelect: true,
        columns: [
            {field: "SessionType", title: "会话类型(英文)", align: "center", valign: "middle", sortable: "true", visible: false},
            {field: "SessionTypeZh", title: "会话类型", align: "center", valign: "middle", sortable: "true"},
            {field: "SessionId", title: "会话ID", align: "center", valign: "middle", sortable: "true"},
            {field: "SessionNick", title: "会话昵称", align: "center", valign: "middle", sortable: "true"},
            {field: "SessionImage", title: "会话头像", align: "center", valign: "middle", sortable: "true", visible: false},
            {field: "C2cAccount", title: "发送者ID", align: "center", valign: "middle", sortable: "true"},
            {field: "C2cNick", title: "发送者昵称", align: "center", valign: "middle", sortable: "true"},
            {field: "UnreadMsgCount", title: "未读数", align: "center", valign: "middle", sortable: "true"},
            {field: "MsgSeq", title: "Seq", align: "center", valign: "middle", sortable: "true"},
            {field: "MsgRandom", title: "Random", align: "center", valign: "middle", sortable: "true"},
            {field: "MsgTimeStamp", title: "时间", align: "center", valign: "middle", sortable: "true"},
            {field: "MsgShow", title: "内容", align: "center", valign: "middle", sortable: "true"}
        ],
        data: data,
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

//我的最近联系人
var getRecentContactList = function () {
    initGetRecentContactListTable([]);
    var options = {
        'Count': reqRecentSessCount//最近的会话数
    };
    webim.getRecentContactList(
        options,
        function (resp) {
        	//清空聊天对象列表
        	console.log(resp)
            var data = [];
            var tempSess,tempSessMap={};//临时会话变量
            if (resp.SessionItem && resp.SessionItem.length > 0) {
            	var NewId=true;
            	var IdList= new Array();
            	for (var i in resp.SessionItem) {
            		IdList.push(resp.SessionItem[i].To_Account)
            		if(window.localStorage.getItem('identifier')==resp.SessionItem[i].To_Account){
            			NewId=false;
            		}
            	}
				var TagList2=new Array();
				TagList2.push('Tag_Profile_IM_Nick');
				TagList2.push('Tag_Profile_IM_Image');
				var param2 ={"To_Account": IdList,"TagList": TagList2};
				var IdList2=new Array();
            	$.ajax({
						type:"POST",
						url:"https://console.tim.qq.com/v4/profile/portrait_get?usersig=eJxlj11rgzAARd-9FZJXx8xHY9u9FRXWzkHdOnF9EWkSzdQYbFZ0o-99mytU6H0953K535Zt22AXvd7nh0P7qUxmBs2B-WADCO6uUGvJstxkpGM3kPdadjzLheHdCBGlFEM4dSTjykghL0bOGqkm*MiqbNz4789*yxgv0WyqyGKEz*G7v46DhCAznyeBt3SclpKuiKOvFRyaBal9Wr*k*2TDQzdFqROvy1W0FUXVO*VC70ujQm*oq37nxl6CBXxyN*LNDz4eyUltPT2ZNLLhl0OQEEg8Qif0xLujbNUoYIgowgT*BVhn6wc3G1tt&identifier=admin&sdkappid="+loginInfo.sdkAppID+"&random="+Math.floor(Math.random()*1000)+"&contenttype=json",
						async:false,
						data:JSON.stringify(param2),
						success:function(data){
							IdList2=JSON.parse(data).UserProfileItem
						}
					});
            	if(NewId){
            		var ajaxId =new Array();
					ajaxId.push(window.localStorage.getItem('identifier'));
					var TagList=new Array();
					TagList.push('Tag_Profile_IM_Nick');
					TagList.push('Tag_Profile_IM_Image');
					var param ={"To_Account": ajaxId,"TagList": TagList};
	            	$.ajax({
						type:"POST",
						url:"https://console.tim.qq.com/v4/profile/portrait_get?usersig=eJxlj11rgzAARd-9FZJXx8xHY9u9FRXWzkHdOnF9EWkSzdQYbFZ0o-99mytU6H0953K535Zt22AXvd7nh0P7qUxmBs2B-WADCO6uUGvJstxkpGM3kPdadjzLheHdCBGlFEM4dSTjykghL0bOGqkm*MiqbNz4789*yxgv0WyqyGKEz*G7v46DhCAznyeBt3SclpKuiKOvFRyaBal9Wr*k*2TDQzdFqROvy1W0FUXVO*VC70ujQm*oq37nxl6CBXxyN*LNDz4eyUltPT2ZNLLhl0OQEEg8Qif0xLujbNUoYIgowgT*BVhn6wc3G1tt&identifier=admin&sdkappid="+loginInfo.sdkAppID+"&random="+Math.floor(Math.random()*1000)+"&contenttype=json",
						async:false,
						data:JSON.stringify(param),
						success:function(data){
							
							var Jdata = JSON.parse(data).UserProfileItem[0].ProfileItem;
							
							var Jname,Jimgurl;
							if(Jdata != undefined){
								for(let i in Jdata){
									if(Jdata[i].Tag=="Tag_Profile_IM_Nick"){
										Jname=Jdata[i].Value;
										if(Jname==''){
											Jname=window.localStorage.getItem('identifier');
										}
									}
									if(Jdata[i].Tag=="Tag_Profile_IM_Image"){
										Jimgurl=Jdata[i].Value;
										if(Jimgurl==''){
											Jimgurl='img/friend.jpg';
										}
										
									}
								}
							}
							else{
								Jname=window.localStorage.getItem('identifier');
								Jimgurl='img/friend.jpg';
								
							}
							
             
						}
					});
            	}
            	let myAccount=window.localStorage.getItem('identifier');
            	let SessionItem = resp.SessionItem;
            	for (let jj = 0; jj < SessionItem.length; jj++) {
                    	if(myAccount==SessionItem[jj].Info_Account){
                    		SessionItem.splice(jj,1);
                    		jj=0;
                    	}
                    }
            	console.log(SessionItem);
                for (var i in SessionItem) {
                	
                    var item = SessionItem[i];
                    var type = item.Type;//接口返回的会话类型
                    var sessType,typeZh, sessionId, sessionNick='', sessionImage='', senderId='', senderNick='';
                   	typeZh = '私聊';
                    sessType=webim.SESSION_TYPE.C2C;//设置会话类型
                    sessionId = item.To_Account;//会话id，私聊时为好友ID或者系统账号（值为@TIM#SYSTEM，业务可以自己决定是否需要展示），注意：从To_Account获取,

                    if(sessionId=='@TIM#SYSTEM'){//先过滤系统消息，，
                        webim.Log.warn('过滤好友系统消息,sessionId='+sessionId);
                        continue;
                    }
                    var key=sessType+"_"+sessionId;
                    for(let j in IdList2){
                    	if(IdList2[j].To_Account==sessionId){
                    		
                    		if(IdList2[j].ProfileItem != undefined){
                    			let Jdata2 =IdList2[j].ProfileItem;
                    			
								for(let ii in Jdata2){
									if(Jdata2[ii].Tag=="Tag_Profile_IM_Nick"){
										sessionNick=Jdata2[ii].Value;
										if(sessionNick==''){
											sessionNick=window.localStorage.getItem('identifier');
										}
									}
									if(Jdata2[ii].Tag=="Tag_Profile_IM_Image"){
										sessionImage=Jdata2[ii].Value;
										if(sessionImage==''){
											sessionImage='img/friend.jpg';
										}
										
									}
								}
							}
							else{
								sessionNick=IdList2[j].To_Account;
								sessionImage='img/friend.jpg';
								
							}
                    	}
                    }
                    
                    
                    senderId=senderNick='';//私聊时，这些字段用不到，直接设置为空
               		addSess(sessType,webim.Tool.formatText2Html(sessionId), webim.Tool.formatText2Html(sessionNick), sessionImage, item.UnreadMsgCount, 'sesslist');
             
                    
                }
                
                
            }
            console.log('1')
             webim.syncMsgs(onMsgNotify);//初始化最近会话的消息未读数
                
        },
        function (err) {
            alert(err.ErrorInfo);
        }
    );
};

//初始化聊天界面左侧最近会话列表
var initRecentContactList = function (cbOK, cbErr) {

    var options = {
        'Count': reqRecentSessCount//要拉取的最近会话条数
    };
    webim.getRecentContactList(
        options,
        function (resp) {
        	console.log(resp)
            var mid=[];//临时会话变量
			for (var i in resp.SessionItem) {
                var item = resp.SessionItem[i];
                mid.push(item.To_Account)

            }
			console.log(mid)
//			var messagelis=[];
			var messagelis=[{"uid":"512","im_identifier":"IM512","username":"穆穆客服","head_img":"https://www.mmuwang.com/Public/Upload/head/2017-11-28/s_5a1d1e977e3cd.jpg"},{"uid":"515","im_identifier":"IM515","username":"奔跑者","head_img":"http://mumu.nana1909.xin/Public/Upload/head/2017-11-20/wx_1511166186175.jpeg"},{"uid":"773","im_identifier":"IM773","username":"楊杨阳","head_img":"http://mumu.nana1909.xin/Public/Upload/head/2017-11-24/s_5a1792bf6bb40.JPG"},{"uid":"1000","im_identifier":"IM1000","username":"越長大~越孤單","head_img":"http://mumu.nana1909.xin/Public/Upload/head/2017-11-29/s_5a1e75510609d.jpg"},{"uid":"1000","im_identifier":"IM1000","username":"越長大~越孤單","head_img":"http://mumu.nana1909.xin/Public/Upload/head/2017-11-29/s_5a1e75510609d.jpg"},{"uid":"1000","im_identifier":"IM1000","username":"越長大~越孤單","head_img":"http://mumu.nana1909.xin/Public/Upload/head/2017-11-29/s_5a1e75510609d.jpg"}];     
//			$.ajax({
//				type:"post",
//				url:"http://mumu.nana1909.com/api/im/getImContactsList",
//				async:false,
//				data:{
//					'im_identifier':mid
//				},
//				success:function(data){
//					messagelis=data.data.data.list;
//				}
//				
//			});
            //清空聊天对象列表
            var sessList = document.getElementsByClassName("sesslist")[0];
            sessList.innerHTML = "";
            if (resp.SessionItem && resp.SessionItem.length > 0) {//如果存在最近会话记录

                for (var i in resp.SessionItem) {
                	var item = resp.SessionItem[i];
                   	addSess('C2C',item.To_Account,messagelis[i].username, messagelis[i].head_img, item.UnreadMsgCount, 'sesslist','',item.MsgTimeStamp,item.MsgShow);

                }
               

            }
            webim.syncMsgs(onMsgNotify);//初始化最近会话的消息未读数

        },
        cbErr
    );
};

//初始化最近会话的消息未读数
function initUnreadMsgCount(){
    var sess;
    var sessMap=webim.MsgStore.sessMap();
    for (var i in sessMap) {
        sess = sessMap[i];
        if (selToID && selToID != sess.id()) {//更新其他聊天对象的未读消息数
            updateSessDiv(sess.type(), sess.id(), sess.name(), sess.unread());
        }
    }
}

